﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GSLMS.Services.Interface;
using System.Threading;
using GSLMS.Entity;
using GSLMS.Core;
using GSLMS.Entity.DTO;

namespace GSLMS.WebAPP.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        protected string ajaxStr = "\"statusCode\":\"{0}\", \"message\":\"{1}\", \"navabId\":\"{2}\", \"forwardUrl\":\"{3}\", \"callbackType\":\"{4}\"";

        private static readonly ISYS_EMP serviceEmp = ServiceFactory.GetService<ISYS_EMP>("ISYS_EMP");
        //private static readonly IRole servicesManager = ServiceFactory.GetService<IRole>();
        [HttpGet]
        public ActionResult Index()
        {
            Thread thread = new Thread(new ThreadStart(DelTempFiles));
            thread.Start();

            if (Session["CurentUser"] != null)
            {
                new RedirectResult("main");
            }
            return View(new TB_SYS_EMP());
        }
        public ActionResult Out()
        {
            Session["CurentUser"] = null;
            Session.Abandon();
            Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);
            return View("Index", new TB_SYS_EMP());
        }
        [HttpPost]
        public string validate(FormCollection collection)
        {
            string code = Request["code"];
            if (Session["ValidateCode"] == null)
            {
                ajaxStr = string.Format(ajaxStr, 301, ResourceManager.ValidateTimeOut, "Login", "", "");
            }
            else
            {
                //if (code != Session["ValidateCode"].ToString())
                //{
                //    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.ValidateFail, "Login", "", "");
                //}
                //else
                //{
                    TB_SYS_EMP model = new TB_SYS_EMP();
                    string userName="";
                    string pwd="";

                    userName=Request["User"].Trim();
                    pwd=Request["Pwd"].Trim();


                   // model = serviceEmp.CheckLogin(userName, pwd);
                    model = serviceEmp.GetByUserName(userName);

                    #region 测试代码

                    if (model == null)
                    {
                        model = new TB_SYS_EMP();
                    }

                    model.USERNAME = userName=="" ? "admin" : userName;
                    model.USERSTATUS = 1;
                    model.IsLogin = true;
                    model.USERTYPE = 1;
                    
                    #endregion
                  


                    if (model.USERNAME==null||model.USERNAME == "")
                    { 
                      //用户不存在
                        ajaxStr = string.Format(ajaxStr, 300,"用户不存在。", "Login", "", "");
                    }
                    else if (!model.IsLogin)
                    { 
                      //用户名或密码错误
                        ajaxStr = string.Format(ajaxStr, 300, "用户名或密码错误。", "Login", "", "");
                    }
                    else if (model.USERSTATUS == 0)
                    {
                        //用户已经被冻结
                        ajaxStr = string.Format(ajaxStr, 300, "用户已经被冻结，请与管理员联系。", "Login", "", "");
                    }
                    else
                    { 
                      //登录成功
                        GetRoles(model);
                        WriteLog(model.USERNAME,pwd,model.IsLogin);
                        ajaxStr = string.Format(ajaxStr, 200, "登录成功", "Login", "", "");
                    }

                   
                //}
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }


        public void GetRoles(TB_SYS_EMP model)
        {
            CurrentUserDTO curentUser = new CurrentUserDTO();
            if (model.USERTYPE==1)
            {

                curentUser.CurrentUserInfo = model;
                List<VRolePurview> roles = GetRolesFromXML();
                curentUser.Roles = roles;

                
            }
            else
            {
                //获取菜单XML信息
               // curentUser = servicesManager.GetByUserAndRoles(model.User);
            }
            Session["CurentUser"] = curentUser;
            Response.Cookies["user"].Value = curentUser.CurrentUserInfo.USERNAME;
        }

        private static List<VRolePurview> GetRolesFromXML()
        {
            List<VRolePurview> roles = new List<VRolePurview>();
            var allRoles = HelperCommon.GetModulesFromXML().Where(c => c.Reverse == false || !c.Reverse.HasValue);
            foreach (var c in allRoles)
            {
                roles.Add(
                    new VRolePurview()
                    {
                        Name = "超级管理员",
                        ModulelID = c.ID,
                        ID = c.ID,
                        Title = c.Title,
                        Url = c.Url,
                        Order = c.Order,
                        Remark = c.Remark,
                        GUID = c.GUID,
                        Types = c.Types,
                        ParmFormat = c.ParmFormat,
                        OnCilck = c.OnCilck,
                        Parent = c.Parent,
                        RoleID = -1,
                        CssClass = c.CssClass,
                        Target = c.Target,
                        Fresh = c.Fresh,
                        External = c.External,
                        ModuleName = c.ModuleName,
                        Warn = c.Warn,
                        CallBack = c.CallBack

                    }
                    );
            }
            return roles;
        }


        void WriteLog(string UserName, string pwd, bool isSuccess)
        {
            var logOp = new OperationLogDTO();
            logOp.ID = null;
            logOp.ModuleName = "登录";
            logOp.URL = Request.FilePath;
            logOp.Detail = string.Format("{0}登录，密码：{1},是否成功:{2}", UserName, pwd, isSuccess);
            logOp.Operater = UserName;
            logOp.OpTime = DateTime.Now;

            string parameters = string.Empty;
            foreach (var item in Request.RequestContext.RouteData.Values)
            {
                parameters += string.Format("{0}={1};", item.Key, item.Value);
            }
            logOp.Parameters = parameters;
            logOp.OperateAction = Request.HttpMethod;

            string xml = XmlUtil.Serializer<OperationLogDTO>(logOp);
            WriteFile wFile = new WriteFile("/OpLog/", LogType.Daily);
            wFile.Write(new Msg() { Text = xml });
        }

        private void DelTempFiles()
        {
            DelTempFile deltempfile = DelTempFile.Instance;
            deltempfile.DelFile();

        }

    }
}
